package com.birdboot.core;

import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

/**
 *
 * */
public class DispatcherServlet {
    //单例模式
    private static DispatcherServlet instance = new DispatcherServlet();
    private DispatcherServlet(){}
    public static DispatcherServlet getInstance(){ return instance; }

    private static File baseDir;
    private static File staticDir;
    static {
        try {
            baseDir = new File(DispatcherServlet.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(baseDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public void service(HttpServletRequest request, HttpServletResponse response){
        String path = request.getUri();
        System.out.println("抽象路径"+path);
        if("/favicon.ico".equals(path)){
            return;
        }

        File file = new File(staticDir,path);
        if(!file.isFile()){
            response.setStatusCode(404);
            response.setStatusReason("Not Found");
            file = new File(staticDir,"/404.html");
        }
        response.setContentFile(file);
        try {
            response.response();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
